package com.example.administrator.websocketdemo.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.example.administrator.websocketdemo.socket.SocketClient;
import com.example.administrator.websocketdemo.socket.SocketListener;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * 功能描述：处理"长链接"相关操作的Service
 */
public class SocketService extends Service implements SocketListener {
    //长链接地址
    private String wsUrl = "";
    //长连接对象
    private SocketClient mClient;

    @Override
    public void onCreate() {
        super.onCreate();
        //开启长连接
        connect();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //关闭长连接
        disconnect();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 开启长链接
     */
    private void connect() {
        try {
            mClient = new SocketClient(new URI(wsUrl));
            mClient.setSocketListener(this);
            mClient.connect();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭长链接
     */
    private void disconnect() {
        if (mClient == null)
            return;

        if (mClient.isOpen())
            mClient.close();

        mClient.removeTimer();
        mClient = null;
    }

    /**
     * 长连接断开时的回调
     */
    @Override
    public void onDisconnected() {
        //重新开启连接
        connect();
    }
}
